//
//  LiveStreamListViewModel.swift
//  live
//
//  Created by melvyn on 2018/8/17.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa
import Link
import RxDataSources

typealias LiveTable = SectionModel<String, LiveStreamViewModel>

final class LiveStreamListViewModel: RxViewModel {
    
    let title: Driver<String?>
    let sections: Driver<[LiveTable]>
    let refresh: PublishSubject<Void> = PublishSubject()
    let isLoading: Driver<Bool>
    
    private let disposeBag: DisposeBag = DisposeBag()
    
    init() {
        title = BehaviorRelay(value: Localized("直播")).asDriver()
        
        let _isLoading = ActivityIndicator.init()
        isLoading = _isLoading.asDriver()
        
        sections = refresh.flatMapLatest({
            AppManager.default.API.requestLiveStreams().trackActivity(_isLoading)
        })
            .map({ $0.value })
            .unwrap()
            .map { $0.map { LiveStreamViewModel.init($0) } }
            .map { [LiveTable(model: "", items: $0)] }
            .asDriver(onErrorJustReturn: [])
        
        refresh.onNext(())
    }
}


class LiveStreamViewModel {
    
    let title: Driver<String?>
    let thumbnail: Driver<Thumbnail>
    let numberOfVisits: Driver<String?>
    let up: Driver<String?>
    let tag: Driver<String?>
    
    let liveStream: BehaviorRelay<LiveStream>
    
    init(_ model: LiveStream) {
        liveStream = BehaviorRelay.init(value: model)
        
        title = liveStream.map({ $0.title })
            .asDriver(onErrorJustReturn: nil)
        
        thumbnail = liveStream
            .map({ ($0.thumbnail, "default_img_34x31_") })
            .asDriver(onErrorJustReturn: (nil, "default_img_34x31_"))
        
        numberOfVisits = liveStream.map({ $0.numberOfVisits })
            .map({ $0 ?? 0 })
            .map({ "\($0)" })
            .asDriver(onErrorJustReturn: "0")
        
        up = liveStream.map({ $0.upload?.nickname })
            .asDriver(onErrorJustReturn: nil)
        
        tag = liveStream.map({ $0.tag })
            .asDriver(onErrorJustReturn: nil)
    }
}
